package com.cml.batisext.core.repository.mybatis.base.sqlprovider;

import java.lang.reflect.Field;
import java.util.List;

import com.cml.batisext.core.repository.mybatis.annotations.DbField;
import com.cml.batisext.core.repository.mybatis.annotations.DbTable;
import com.cml.batisext.core.repository.mybatis.base.BaseDaoSqlProvider;
import com.cml.batisext.util.Contants;

/**
 * 通用接口的insert方法的sql生成器
 * @author lwh
 *
 */
public class BaseDaoInsertSqlProvider extends BaseDaoSqlProvider{

	@Override
    public String doBuildSql(Object param,Class<?> beanType) throws Exception {
		
		String tableName = beanType.getAnnotation(DbTable.class).table();
		
		List<Field> fields = getAllDbField(beanType);
		
		String sqlField = "  ";
		String sqlValues = "  ";
		String tmpColumnName = null;
		Class<?> tmpColumnType = null;
		Object fieldValue = null;
		for(Field f : fields){
			
			DbField field = f.getAnnotation(DbField.class);
			//只对标注了为数据库字段的属性进行处理
			if(field == null){
				continue;
			}
			
			tmpColumnName = getColumnName(f, field);
            //新增时id由数据库自增
            if ("`id`".equals(tmpColumnName)) {
                continue;
            }
			tmpColumnType = getColumnType(f, field);
			fieldValue = getColumnValue(param,f,beanType);
			
			if ("`version`".equals(tmpColumnName)) {
				fieldValue = Contants.VERSION;
			}
			
			if(fieldValue == null){
				continue;
			}
			
			sqlField += tmpColumnName + ",";
			
			sqlValues += setupFieldValue(tmpColumnType, fieldValue) + ",";
		}
		
		
		String sql = "insert into " + tableName + "(" + sqlField.substring(0,sqlField.length() - 1) + ") values(" + sqlValues.substring(0,sqlValues.length() - 1) + ")";
		return sql;
	}
	
}
